﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using DG.Tweening;
using System;

/// <summary>
/// 开场剧情
/// </summary>
public class ClinicRoomController : Singleton<ClinicRoomController>
{

    public Action<eHospitalGame> _onMiniGameStartReady;

    private AnimatorEx m_door_animatorEx;
    private AnimatorEx m_ledi_animatorEx;
    private AnimatorEx m_current_animatorEx;

    private Transform m_currentTarget;
    private Vector3 m_currenttargetPostion;
    private Quaternion m_currenttargetRotation;
    private Transform initTrans;
    private Transform yiziTrans;

    HospitalResManager resIns;
    DOTweenPath dOTweenPath;

    Transform aisha_tuizhong;

    public eHospitalGame m_currentHospitalGame;

    Vector3[] path;
    bool isDoorOpened;
    bool isWalkIn;
    const float InZ = -2.507f;
    const float OutZ = -4.65f;
    float pathTweenDur;

    public override void Init()
    {
        base.Init();

        resIns = HospitalResManager.Instance;
        m_door_animatorEx = new AnimatorEx(resIns.m_door.gameObject);
        m_ledi_animatorEx = new AnimatorEx(resIns.m_lediRoot.gameObject);
        initTrans = resIns.GetAnchorPoint("InitPoint");
        yiziTrans = resIns.GetAnchorPoint("SitPoint");
        dOTweenPath = resIns.GetAnchorPoint("WayMain").GetComponent<DOTweenPath>();
        path = dOTweenPath.wps.ToArray();

        HospitalEventHandler.Instance.AddEventHandler(HospitalEventID.SMALLGAME_OVER, OnSmallGameExit);
        HospitalEventHandler.Instance.AddEventHandler(HospitalEventID.SMALLGAME_FORCEOVER, OnSmallGameFoceExit);

        //PlaySoundWithLedi(HospitalConsts.audio_ledi_huanying, null);

        //StartGame(eHospitalGame.game_vaccine);
        RandomStartAMiniGame();

    }

    public override void UnInit()
    {
        base.UnInit();

        HospitalEventHandler.Instance.RemoveEventHandler(HospitalEventID.SMALLGAME_OVER, OnSmallGameExit);
        HospitalEventHandler.Instance.RemoveEventHandler(HospitalEventID.SMALLGAME_FORCEOVER, OnSmallGameFoceExit);
    }

    public void OnUpdate()
    {

        LowFeverController.Instance.OnUpdate();
        if (Input.GetKeyDown(KeyCode.Alpha7))
        {
            
        }
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            m_currentTarget = resIns.m_nuowaRoot;
            m_current_animatorEx = new AnimatorEx(m_currentTarget.gameObject);
            m_currentTarget.SetActive(true);
            m_currentTarget.transform.rotation = resIns.m_yizi.rotation;
            m_currentTarget.transform.position = resIns.GetAnchorPoint("SitPoint").position;

            StartGameTest(eHospitalGame.game_Stomachache);
        }

        if (Input.GetKeyDown(KeyCode.Alpha3))
        {
            m_currentTarget = resIns.m_nuowaRoot;
            m_current_animatorEx = new AnimatorEx(m_currentTarget.gameObject);
            m_currentTarget.SetActive(true);
            m_currentTarget.transform.rotation = resIns.m_yizi.rotation;
            m_currentTarget.transform.position = resIns.GetAnchorPoint("SitPoint").position;

            StartGameTest(eHospitalGame.game_Toothache);
        }

        if (Input.GetKeyDown(KeyCode.Alpha9))
        {
            m_currentTarget = resIns.m_aishaRoot.transform;
            m_current_animatorEx = new AnimatorEx(m_currentTarget.gameObject);
            m_currentTarget.SetActive(true);
            m_currentTarget.transform.rotation = resIns.m_yizi.rotation;
            m_currentTarget.transform.position = resIns.GetAnchorPoint("SitPoint").position;

            StartGameTest(eHospitalGame.game_vaccine);
        }

        if (Input.GetKeyDown(KeyCode.S))
        {
            StartGame(eHospitalGame.game_Stomachache);
        }

        if (Input.GetKeyDown(KeyCode.F))
        {
            TimerManager.Instance.RemoveAllTimer();
            OnSmallGameExit();
        }

        if (m_currentTarget != null && m_current_animatorEx != null && m_ledi_animatorEx != null)
        {
            m_current_animatorEx.OnUpdate();
            m_ledi_animatorEx.OnUpdate();

            if (isWalkIn)
            {
                if (m_currentTarget.position.z >= OutZ && m_currentTarget.position.z < InZ)
                {
                    if (!isDoorOpened)
                    {
                        isDoorOpened = true;
                        m_door_animatorEx.CrossFade("doorOpen", 0f);
                        PlaySound(HospitalConsts.audio_door_open);
                    }
                }
                else if (m_currentTarget.position.z >= InZ)
                {
                    if (isDoorOpened)
                    {
                        isDoorOpened = false;
                        m_door_animatorEx.CrossFade("doorClose", 0f);
                        PlaySound(HospitalConsts.audio_door_open);
                    }
                }
            }
            else
            {
                if (m_currentTarget.position.z <= InZ && m_currentTarget.position.z > OutZ)
                {
                    if (!isDoorOpened)
                    {
                        isDoorOpened = true;
                        m_door_animatorEx.CrossFade("doorOpen", 0f);
                        PlaySound(HospitalConsts.audio_door_open);
                    }
                }
                else if (m_currentTarget.position.z < OutZ)
                {
                    if (isDoorOpened)
                    {
                        isDoorOpened = false;
                        m_door_animatorEx.CrossFade("doorClose", 0f);
                        PlaySound(HospitalConsts.audio_door_open);
                    }
                }
            }
            
        }
    }

    public void StartGameTest(eHospitalGame game)
    {
        m_currentHospitalGame = game;
        switch (game)
        {
            case eHospitalGame.game_Stomachache:
                StomachacheGameManager.Instance.GameStart();
                break;
            case eHospitalGame.game_Toothache:
                ToothacheGameManager.Instance.GameStart();
                break;
            case eHospitalGame.game_vaccine:
                VaccineGameManager.Instance.GameStart();
                break;
            case eHospitalGame.game_Bruise:
                break;
            case eHospitalGame.game_LowFever:
                break;
            case eHospitalGame.game_HighFever:
                break;
            default:
                break;
        }
    }

    public void ResetAll()
    {

    }

    public void StartGame(eHospitalGame game)
    {
        isWalkIn = true;
        m_currentHospitalGame = game;

        switch (game)
        {
            case eHospitalGame.game_Stomachache:
                m_currentTarget = resIns.m_nuowaRoot;
                m_currentTarget.SetActive(true);
                m_current_animatorEx = new AnimatorEx(m_currentTarget.gameObject);
                m_current_animatorEx.CrossFade(eHospitalNuowaAnim.walk_stomachache.ToString(), 0f);
                DoMove();
                break;
            case eHospitalGame.game_Toothache:

                m_currentTarget = resIns.m_nuowaRoot;
                m_currentTarget.SetActive(true);
                m_current_animatorEx = new AnimatorEx(m_currentTarget.gameObject);
                m_current_animatorEx.CrossFade(eHospitalNuowaAnim.walk_tooth.ToString(), 0f);
                DoMove();
                break;
            case eHospitalGame.game_vaccine:

                m_currentTarget = resIns.m_aishaRoot.transform;
                m_currentTarget.SetActive(true);
                aisha_tuizhong = m_currentTarget.Find("201004000@skin_hospital/304060602");
                aisha_tuizhong.SetActive(true);
                m_current_animatorEx = new AnimatorEx(m_currentTarget.gameObject);
                m_current_animatorEx.CrossFade(eHospitalAishaAnim.walk_leg_pain.ToString(), 0f);
                DoMove();
                break;
            case eHospitalGame.game_Bruise:

                m_currentTarget = resIns.m_aishaRoot.transform;
                m_currentTarget.SetActive(true);
                m_current_animatorEx = new AnimatorEx(m_currentTarget.gameObject);
                m_current_animatorEx.CrossFade(eHospitalAishaAnim.Walke.ToString(), 0f);
                DoMove();

                break;
            case eHospitalGame.game_LowFever:
                LowFeverController.Instance.StartGame(1);
                break;
            case eHospitalGame.game_HighFever:
                LowFeverController.Instance.StartGame(2);
                break;
            default:
                break;
        }
    }

    private void DoMove()
    {
        m_currenttargetPostion = m_currentTarget.position;
        m_currenttargetRotation = m_currentTarget.rotation;
        switch (m_currentHospitalGame)
        {
            case eHospitalGame.game_Stomachache:
                pathTweenDur = dOTweenPath.duration;
                break;
            case eHospitalGame.game_Toothache:
                pathTweenDur = dOTweenPath.duration;
                break;
            case eHospitalGame.game_vaccine:
                pathTweenDur = dOTweenPath.duration;
                break;
            case eHospitalGame.game_Bruise:
                pathTweenDur = 8;
                break;
            default:
                break;
        }
        m_currentTarget.DOPath(path, pathTweenDur).SetEase(dOTweenPath.easeType).SetLookAt(.1f).OnComplete(OnWalkInComplete);
    }

    private void OnWalkInComplete()
    {
        m_currentTarget.DORotate(new Vector3(0, 90, 0), .5f).OnComplete(() => {
            switch (m_currentHospitalGame)
            {
                case eHospitalGame.game_Stomachache:
                    m_current_animatorEx.Play(eHospitalNuowaAnim.up_chair.ToString()).OnFinished(() => {
                        m_current_animatorEx.CrossFade(eHospitalNuowaAnim.s_idle_stomachache.ToString(), .1f, () => {
                            PlaySoundWithLedi(HospitalConsts.audio_ledi_xunwen, () => {
                                string audiopath = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, HospitalConsts.audio_nuowa_duziteng);
                                m_current_animatorEx.PlaySequence(eHospitalNuowaAnim.s_t_stomachache_01.ToString(), audiopath, () =>
                                {
                                    m_current_animatorEx.CrossFade(eHospitalNuowaAnim.s_idle_stomachache.ToString(), .1f);
                                    audiopath = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, HospitalConsts.audio_ledi_zhiliao_duzi);
                                    m_ledi_animatorEx.PlaySequence(eHospitalLediAnim.BeginTalk.ToString(), audiopath, () =>
                                    {
                                        if (_onMiniGameStartReady != null) _onMiniGameStartReady(m_currentHospitalGame);
                                    });
                                });
                            });
                            
                        });
                    });
                    break;
                case eHospitalGame.game_Toothache:
                    m_current_animatorEx.Play(eHospitalNuowaAnim.up_chair.ToString()).OnFinished(() => {
                        m_current_animatorEx.CrossFade(eHospitalNuowaAnim.s_idle_tooth.ToString(), .1f, () => {
                            PlaySoundWithLedi(HospitalConsts.audio_ledi_xunwen, () => {
                                string audiopath = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, HospitalConsts.audio_nuowa_yateng);
                                m_current_animatorEx.PlaySequence(eHospitalNuowaAnim.s_all_talk_tooth_01.ToString(), audiopath, () =>
                                {
                                    m_current_animatorEx.CrossFade(eHospitalNuowaAnim.s_idle_tooth.ToString(), .1f);
                                    audiopath = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, HospitalConsts.audio_ledi_zhiliao_yimiao);
                                    m_ledi_animatorEx.PlaySequence(eHospitalLediAnim.BeginTalk.ToString(), audiopath, () =>
                                    {
                                        if (_onMiniGameStartReady != null) _onMiniGameStartReady(m_currentHospitalGame);
                                    });
                                });
                            });
                        });
                    });

                    break;
                case eHospitalGame.game_vaccine:
                    m_current_animatorEx.gameObject.transform.DOLocalMove(new Vector3(.268f, .108f, -1.2195f), 4f);
                    m_current_animatorEx.Play(eHospitalAishaAnim.cli_chair.ToString()).OnFinished(() => {
                        m_current_animatorEx.CrossFade(eHospitalAishaAnim.s_idle.ToString(), .1f);
                        string audiopath = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, HospitalConsts.audio_aisha_shuaidao);
                        PlaySoundWithLedi(HospitalConsts.audio_ledi_xunwen, () => {
                            m_current_animatorEx.PlaySequence(eHospitalAishaAnim.all_talk_s_fear_01.ToString(), audiopath, () =>
                            {
                                m_current_animatorEx.CrossFade(eHospitalAishaAnim.s_idle.ToString(), .1f);
                                audiopath = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, HospitalConsts.audio_ledi_tui_zhiliao);
                                m_ledi_animatorEx.PlaySequence(eHospitalLediAnim.BeginTalk.ToString(), audiopath, () =>
                                {
                                    if (_onMiniGameStartReady != null) _onMiniGameStartReady(m_currentHospitalGame);
                                });
                            });
                        });
                    });
                    break;
                case eHospitalGame.game_Bruise:
                    m_current_animatorEx.gameObject.transform.DOLocalMove(new Vector3(.268f, .108f, -1.2195f), 4f);
                    m_current_animatorEx.Play(eHospitalAishaAnim.cli_chair.ToString()).OnFinished(() => {
                        m_current_animatorEx.CrossFade(eHospitalAishaAnim.s_idle.ToString(), .1f);
                        PlaySoundWithLedi(HospitalConsts.audio_ledi_xunwen, () => {
                            string audiopath = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, RandomPlayAudio());
                            m_current_animatorEx.PlaySequence(eHospitalAishaAnim.all_talk_s_fear_01.ToString(), audiopath, () =>
                            {
                                m_current_animatorEx.CrossFade(eHospitalAishaAnim.s_idle.ToString(), .1f);
                                audiopath = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, HospitalConsts.audio_ledi_zhiliao_duzi);
                                m_ledi_animatorEx.PlaySequence(eHospitalLediAnim.BeginTalk.ToString(), audiopath, () =>
                                {
                                    if (_onMiniGameStartReady != null) _onMiniGameStartReady(m_currentHospitalGame);
                                });

                            });
                        });
                    });
                    break;
                case eHospitalGame.game_LowFever:
                    break;
                case eHospitalGame.game_HighFever:
                    break;
                default:
                    break;
            }
        });
    }

    private void OnSmallGameFoceExit()
    {
        //关门，移动位置，重新随机进入
        Debug.Log("forceExit");
        Debug.Log(m_currenttargetPostion);
        m_currentTarget.position = m_currenttargetPostion;
        m_currentTarget.rotation = m_currenttargetRotation;

    }

    public void OnSmallGameExit()
    {
        isWalkIn = false;

        //每个小游戏结束自动清除生成的一些物体
        HospitalController.Instance.DestroyCacheObject();

        resIns.m_lediRoot.SetActive(true);
        HospitalResManager.Instance.root.SetActive(true);
        HospitalResManager.Instance.Game_MainRoot.SetActive(true);
        WindowManager.Instance.OpenWindow(WinNames.ClinicRoomPanel);
        string audiopath = "";
        switch (m_currentHospitalGame)
        {
            case eHospitalGame.game_Stomachache:
                Debug.Log("肚子痛小游戏结束");
                audiopath = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, HospitalConsts.audio_nuowa_duzi_ganji);
                m_current_animatorEx.CrossFade(eHospitalNuowaAnim.down_chair.ToString(), .1f, () => {
                    m_current_animatorEx.PlaySequence(eHospitalNuowaAnim.all_talk_goodbye_01.ToString(), audiopath, () =>
                    {
                        audiopath = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, HospitalConsts.audio_ledi_duzitixing);
                        m_ledi_animatorEx.PlaySequence(eHospitalLediAnim.BeginTalk.ToString(), audiopath, () =>
                        {
                            Debug.Log("话讲完了");
                            m_current_animatorEx.CrossFade(eHospitalNuowaAnim.walk.ToString(), 0f);
                            Vector3[] inversePath = HospitalUtil.PathInverse1(path);
                            m_currentTarget.DOPath(inversePath, pathTweenDur).SetEase(dOTweenPath.easeType).SetLookAt(.1f).OnComplete(() => {
                                Debug.Log("角色已经出去了");
                                TimerManager.Instance.AddTimer(1f, () => { m_currentTarget.SetActive(false); });
                                RandomStartAMiniGame();
                            });
                        });
                    });
                });

                break;
            case eHospitalGame.game_Toothache:
                audiopath = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, HospitalConsts.audio_nuowa_ya_fanxing);
                m_current_animatorEx.CrossFade(eHospitalNuowaAnim.down_chair.ToString(), .1f, () => {
                    m_current_animatorEx.PlaySequence(eHospitalNuowaAnim.all_talk_goodbye_01.ToString(), audiopath, () =>
                    {
                        audiopath = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, HospitalConsts.audio_ledi_shuaya_jiaodao);
                        m_ledi_animatorEx.PlaySequence(eHospitalLediAnim.BeginTalk.ToString(), audiopath, () =>
                        {
                            m_current_animatorEx.CrossFade(eHospitalNuowaAnim.walk.ToString(), 0f);
                            Vector3[] inversePath = HospitalUtil.PathInverse1(path);
                            m_currentTarget.DOPath(inversePath, pathTweenDur).SetEase(dOTweenPath.easeType).SetLookAt(.1f).OnComplete(() => {
                                Debug.Log("角色已经出去了");
                                TimerManager.Instance.AddTimer(1f, () => { m_currentTarget.SetActive(false); });
                                RandomStartAMiniGame();
                            });
                        });
                    });
                });

                break;
            case eHospitalGame.game_vaccine:
                m_current_animatorEx.gameObject.transform.DOLocalMove(path[path.Length - 1], 1f).SetEase(Ease.Linear);
                audiopath = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, HospitalConsts.audio_aisha_ganxie);
                m_current_animatorEx.CrossFade(eHospitalAishaAnim.down_chair.ToString(), .1f, () => {
                    m_current_animatorEx.PlaySequence(eHospitalAishaAnim.all_talk_goodbye_01.ToString(), audiopath, () =>
                    {
                        audiopath = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, HospitalConsts.audio_ledi_tui_jiaodao);
                        m_ledi_animatorEx.PlaySequence(eHospitalLediAnim.BeginTalk.ToString(), audiopath, () =>
                        {
                            Debug.Log("话讲完了");
                            m_current_animatorEx.CrossFade(eHospitalAishaAnim.Walke.ToString(), .3f);
                            Vector3[] inversePath = HospitalUtil.PathInverse1(path);
                            m_currentTarget.DOPath(inversePath, pathTweenDur).SetEase(dOTweenPath.easeType).SetLookAt(.1f).OnComplete(() => {
                                Debug.Log("角色已经出去了");

                                aisha_tuizhong.SetActive(false);
                                TimerManager.Instance.AddTimer(1f, () => { GameObject.Destroy(m_currentTarget.gameObject); });
                                RandomStartAMiniGame();
                            });
                        });
                    });
                });

                break;
            case eHospitalGame.game_Bruise:
                m_current_animatorEx.gameObject.transform.DOLocalMove(path[path.Length - 1], 1f).SetEase(Ease.Linear); 
                audiopath = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, HospitalConsts.audio_aisha_dazhenbuteng);
                m_current_animatorEx.CrossFade(eHospitalAishaAnim.down_chair.ToString(), .1f, () => {
                    m_current_animatorEx.PlaySequence(eHospitalAishaAnim.all_talk_goodbye_01.ToString(), audiopath, () =>
                    {
                        audiopath = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, HospitalConsts.audio_ledi_dazheng_jiaodao);
                        m_ledi_animatorEx.PlaySequence(eHospitalLediAnim.BeginTalk.ToString(), audiopath, () =>
                        {
                            Debug.Log("话讲完了");
                            m_current_animatorEx.CrossFade(eHospitalAishaAnim.Walke.ToString(), .3f);
                            Vector3[] inversePath = HospitalUtil.PathInverse1(path);
                            m_currentTarget.DOPath(inversePath, pathTweenDur).SetEase(dOTweenPath.easeType).SetLookAt(.1f).OnComplete(() => {
                                Debug.Log("角色已经出去了");
                                TimerManager.Instance.AddTimer(1f, () => { GameObject.Destroy(m_currentTarget.gameObject); });
                                RandomStartAMiniGame();
                            });
                        });
                    });
                });
                break;
            case eHospitalGame.game_LowFever:
                RandomStartAMiniGame();
                break;
            case eHospitalGame.game_HighFever:
                RandomStartAMiniGame();
                break;
            default:
                break;
        }
    }

    int index = 0;
    public void RandomStartAMiniGame()
    {
        TimerManager.Instance.AddTimer(2f, () => {
            //int index = UnityEngine.Random.Range(0, 6);
            Debug.Log(index);
            StartGame((eHospitalGame)index);
            index++;
            if (index >= 6)
                index = 0;
            //index = 2;
        });
    }

    public void PlaySound(string audioname)
    {
        string path = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, audioname);
        AudioManager.Instance.PlaySound(path);
    }

    public void PlaySoundWithLedi(string audioname,Action callback)
    {
        string audiopath = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, audioname);
        m_ledi_animatorEx.PlaySequence(eHospitalLediAnim.BeginTalk.ToString(), audiopath, callback);
    }

    int timerID;
    public void PlaySound(string audioname, System.Action callback = null, bool stopOtherSound = false, float delay = 0f)
    {
        if (stopOtherSound)
            AudioManager.Instance.StopAllSound();
        string path = FileTools.CombinePath(HospitalConsts.hospitalAudioBasePath, audioname);
        TimerManager.Instance.AddTimer(delay, () => {
            GameAudioSource _audiosource = AudioManager.Instance.PlaySound(path);
            if (callback != null)
            {
                TimerManager.Instance.RemoveTimerSafely(ref timerID);
                timerID = TimerManager.Instance.AddTimer(_audiosource.Length, callback);
            }
        });
    }


    public string RandomPlayAudio()
    {
        
        if (InjectionWindow.Instance.RandomNumber())
        {
            
            return HospitalConsts.audio_aisha_liuganyimiao;
        }
        else
        {
            
            return HospitalConsts.audio_aisha_yilaodayimiao;
        }
        
        
        
    }

}
